<?php
class ApiController extends AppController 
{
    public $components = array("RequestHandler","Emstraining");
    public $uses = array('Cashier','Api','Gift','Voucher');
    public function cashier_info($id) {
        $recipe = $this->Cashier->findById($id);
        $this->set(array(
            "cashier" => $recipe,
            "_serialize" => array("cashier")
        ));
    }
    private function create_accesstoken($username){
        $chars = 'abcdeghijklmnopqrstuvwxyz1234567890';
        $length = 10;
        $chars_length = (strlen($chars) - 1);
        $string = $chars{rand(0, $chars_length)};
        for ($i = 1; $i < $length; $i = strlen($string))
        {
            $r = $chars{rand(0, $chars_length)};
            if ($r != $string{$i - 1}) $string .=  $r;
        }
        $token = md5($string);
        $api = $this->Api->find('first',array('conditions'=>array('access_token'=>$token)));
        if(!empty($api)){
            return $this->create_accesstoken($username);
        }
        return $token;
    }
    public function cashier_login(){
        $username = $_REQUEST['username'];
        $password = $_REQUEST['password'];
        $cashier = $this->Cashier->get_user($username,$password);
        if(!empty($cashier)){
            $api = $this->Api->find('first',array('order'=>'Api.id desc','conditions'=>array('Api.cashier_id'=>$cashier['Cashier']['id'])));
            $access_token='';
            $expired = "";
            if(!empty($api)&&  time()<$api['Api']['expired']){
                $access_token = $api['Api']['access_token'];
                $expired = $api['Api']['expired'];
            }else{
                $access_token = $this->create_accesstoken($username);
                $created = time();
                $expired = strtotime("+5 hours");
                $cashier_id = $cashier['Cashier']['id'];
                $this->Api->create();
                $this->Api->save(array(
                    'cashier_id'=>$cashier_id,
                    'access_token'=>$access_token,
                    'created'=>$created,
                    'expired'=>$expired
                ));

            }
            $return = array(
                'name'=>$cashier['Cashier']['name'],
                'access_token'=>$access_token,
                'expired'   =>$expired
            );
            $this->set(array(
                "success" => $return,
                "_serialize" => array("success")
            ));
        }else{
            $error = array(
                'message'=>'wrong username or password',
                'code'  =>'100'
            );
            $this->set(array(
                "error" => $error,
                "_serialize" => array("error")
            ));
        }
    }
    public function get_voucher_gift() {
        $token=isset($_REQUEST['access_token'])?$_REQUEST['access_token']:"";
        $valid = $this->check_access_token($token);
        if($valid !== false){
            $check = array('code');
            $is_validate=true;
            $field_missing=array();
            foreach ($check as $value) {
                if(isset($_REQUEST[$value])){
                    if(!$_REQUEST[$value]){
                        $is_validate=false;
                        $field_missing[]=$value;
                    }
                }else{
                    $is_validate=false;
                    $field_missing[]=$value;
                }
            }
            if($is_validate !== true){
                $error = array(
                    'message'=>'Missing fields :'.  implode(",", $field_missing),
                    'code'  =>102
                );
                $this->set(array(
                    "error" => $error,
                    "_serialize" => array("error")
                ));
            }else{
                $cashier = $this->get_info($token);
                $voucher = $this->Voucher->find('first',array('conditions'=>array(
                    'code'=>$_REQUEST['code'],
                    'OR'=>array(
                        'expired_date >='=>date('Y-m-d'),
                        'expired_date'=>'0000-00-00'
                    )
                )));
                $gift = $this->Gift->find('first',array('conditions'=>array(
                    'code'=>$_REQUEST['code'],
                    'expiry >='=>date('Y-m-d')
                )));
                $return = array();
                if(!empty($voucher)){
                    $return['voucher']=array(
                        'code'=>$voucher['Voucher']['code'],
                        'expired'=>$voucher['Voucher']['expired_date'],
                        'value' =>$voucher['Voucher']['value']
                    );
                }
                if(!empty($gift)){
                    $return['gift']=array(
                        'code'=>$gift['Gift']['code'],
                        'expired'=>$gift['Gift']['expiry'],
                        'value' =>$gift['Gift']['value']
                    );
                }
                if(!empty($return)){
                    $this->set(array(
                        "success" => $return,
                        "_serialize" => array("success")
                    ));
                }else{
                    $error = array(
                        'message'=>'This code has been expired',
                        'code'  =>101
                    );
                    $this->set(array(
                        "error" => $error,
                        "_serialize" => array("error")
                    ));
                }
            }
            
        }else{
            $error = array(
                'message'=>'Access token invalid/expired',
                'code'  =>101
            );
            $this->set(array(
                "error" => $error,
                "_serialize" => array("error")
            ));
        }
    }
    
    public function add_gift() {
        $token=isset($_REQUEST['access_token'])?$_REQUEST['access_token']:"";
        $valid = $this->check_access_token($token);
        if($valid !== false){
            $check = array('name','expired','value');
            $is_validate=true;
            $field_missing=array();
            foreach ($check as $value) {
                if(isset($_REQUEST[$value])){
                    if(!$_REQUEST[$value]){
                        $is_validate=false;
                        $field_missing[]=$value;
                    }
                }else{
                    $is_validate=false;
                    $field_missing[]=$value;
                }
            }
            if($is_validate !== true){
                $error = array(
                    'message'=>'Missing fields :'.  implode(",", $field_missing),
                    'code'  =>102
                );
                $this->set(array(
                    "error" => $error,
                    "_serialize" => array("error")
                ));
            }else{
                $cashier = $this->get_info($token);
                $this->Gift->create();
                $code = $this->Emstraining->loyalty_gift_number();
                $this->Gift->save(
                    array(
                        'cashier_id'=>$cashier['Api']['cashier_id'],
                        'name'  => urldecode($_REQUEST['name']) ,
                        'code'  =>  $code,
                        'value' =>$_REQUEST['value'],
                        'expiry'=>$_REQUEST['expired'],
                        'created'=>date('Y-m-d H:i:s')
                    )
                );
                $id = $this->Gift->id;
                $gift = $this->Gift->read(null,$id);
                if($gift['Gift']['code'] && $gift['Gift']['cashier_id'] !=0){
                    $return = array(
                        'name'=>urldecode($_REQUEST['name']),
                        'code'=>$code,
                        'value' =>$_REQUEST['value'],
                        'expired'   =>$_REQUEST['expired']
                    );
                    $this->set(array(
                        "success" => $return,
                        "_serialize" => array("success")
                    ));
                }else{
                    $this->Gift->delete($id);
                    $error = array(
                        'message'=>'The gift is not saved. Please try again',
                        'code'  =>103
                    );
                    $this->set(array(
                        "error" => $error,
                        "_serialize" => array("error")
                    ));
                }
            }
            
        }else{
            $error = array(
                'message'=>'Access token invalid/expired',
                'code'  =>101
            );
            $this->set(array(
                "error" => $error,
                "_serialize" => array("error")
            ));
        }
    }
    public function change_gift(){
        $token=isset($_REQUEST['access_token'])?$_REQUEST['access_token']:"";
        $valid = $this->check_access_token($token);
        if($valid !== false){
            $check = array('code','type','value');
            $is_validate=true;
            $field_missing=array();
            foreach ($check as $value) {
                if(isset($_REQUEST[$value])){
                    if(!$_REQUEST[$value]){
                        $is_validate=false;
                        $field_missing[]=$value;
                    }
                }else{
                    $is_validate=false;
                    $field_missing[]=$value;
                }
            }
            if($is_validate !== true){
                $error = array(
                    'message'=>'Missing fields :'.  implode(",", $field_missing),
                    'code'  =>102
                );
                $this->set(array(
                    "error" => $error,
                    "_serialize" => array("error")
                ));
            }else{
                $cashier = $this->get_info($token);
                $gift = $this->Gift->find('first',array('conditions'=>array(
                    'code'=>$_REQUEST['code'],
                    'expiry >='=>date('Y-m-d')
                )));
                if(!empty($gift)){
                    $this->Gift->id = $gift['Gift']['id'];
                    if($_REQUEST['type']=="add"){
                        $new_value = $_REQUEST['value']+$gift['Gift']['value'];
                        if($this->Gift->saveField('value',$new_value)){
                            $return = array(
                                'code'=>$_REQUEST['code'],
                                'name'=>$gift['Gift']['name'],
                                'new_value'=>$new_value,
                                'expired'   =>$gift['Gift']['expiry']
                            );
                            $this->set(array(
                                "success" => $return,
                                "_serialize" => array("success")
                            ));
                        }else{
                            $error = array(
                                'message'=>'Can not save the change ! Please try again',
                                'code'  =>103
                            );
                            $this->set(array(
                                "error" => $error,
                                "_serialize" => array("error")
                            ));
                        }
                        
                    }elseif ($_REQUEST['type']=="deduct") {
                        $new_value = $gift['Gift']['value']-$_REQUEST['value'];
                        if($new_value<0){
                            $error = array(
                                'message'=>'The value to deduct must be lower than the value of gift card',
                                'code'  =>103
                            );
                            $this->set(array(
                                "error" => $error,
                                "_serialize" => array("error")
                            ));
                        }else{
                            if($this->Gift->saveField('value',$new_value)){
                                $return = array(
                                    'code'=>$_REQUEST['code'],
                                    'name'=>$gift['Gift']['name'],
                                    'new_value'=>$new_value,
                                    'expired'   =>$gift['Gift']['expiry']
                                );
                                $this->set(array(
                                    "success" => $return,
                                    "_serialize" => array("success")
                                ));
                            }else{
                                $error = array(
                                    'message'=>'Can not save the change ! Please try again',
                                    'code'  =>103
                                );
                                $this->set(array(
                                    "error" => $error,
                                    "_serialize" => array("error")
                                ));
                            }
                        }
                    }else{
                        $error = array(
                                'message'=>'Invalid parameter "type" , must be add or deduct ',
                                'code'  =>103
                            );
                            $this->set(array(
                                "error" => $error,
                                "_serialize" => array("error")
                            ));
                    }
                }else{
                    $error = array(
                        'message'=>'The gift code is invalid or expired. Please try again',
                        'code'  =>103
                    );
                    $this->set(array(
                        "error" => $error,
                        "_serialize" => array("error")
                    ));
                }
                
            }
            
        }else{
            $error = array(
                'message'=>'Access token invalid/expired',
                'code'  =>101
            );
            $this->set(array(
                "error" => $error,
                "_serialize" => array("error")
            ));
        }
    }
    public function sell_voucher(){
        $token=isset($_REQUEST['access_token'])?$_REQUEST['access_token']:"";
        $valid = $this->check_access_token($token);
        if($valid !== false){
            $check = array('code','value');
            $is_validate=true;
            $field_missing=array();
            foreach ($check as $value) {
                if(isset($_REQUEST[$value])){
                    if(!$_REQUEST[$value]){
                        $is_validate=false;
                        $field_missing[]=$value;
                    }
                }else{
                    $is_validate=false;
                    $field_missing[]=$value;
                }
            }
            if($is_validate !== true){
                $error = array(
                    'message'=>'Missing fields :'.  implode(",", $field_missing),
                    'code'  =>102
                );
                $this->set(array(
                    "error" => $error,
                    "_serialize" => array("error")
                ));
            }else{
                $cashier = $this->get_info($token);
                $voucher = $this->Voucher->find('first',array('conditions'=>array(
                    'code'=>$_REQUEST['code'],
                    'OR'=>array(
                        'expired_date >='=>date('Y-m-d'),
                        'expired_date'=>'0000-00-00'
                    )
                )));
                if(!empty($voucher)){
                    $this->Voucher->id = $voucher['Voucher']['id'];
                    $new_value = $voucher['Voucher']['value']-$_REQUEST['value'];
                    if($new_value<0){
                        $error = array(
                            'message'=>'The value to deduct must be lower than the value of voucher card',
                            'code'  =>103
                        );
                        $this->set(array(
                            "error" => $error,
                            "_serialize" => array("error")
                        ));
                    }else{
                        if($this->Voucher->saveField('value',$new_value)){
                            $return = array(
                                'code'=>$_REQUEST['code'],
                                'new_value'=>$new_value,
                                'expired'   =>$voucher['Voucher']['expired_date']
                            );
                            $this->set(array(
                                "success" => $return,
                                "_serialize" => array("success")
                            ));
                        }else{
                            $error = array(
                                'message'=>'Can not save the change ! Please try again',
                                'code'  =>103
                            );
                            $this->set(array(
                                "error" => $error,
                                "_serialize" => array("error")
                            ));
                        }
                    }
                }else{
                    $error = array(
                        'message'=>'The voucher code is invalid or expired. Please try again',
                        'code'  =>103
                    );
                    $this->set(array(
                        "error" => $error,
                        "_serialize" => array("error")
                    ));
                }
                
            }
            
        }else{
            $error = array(
                'message'=>'Access token invalid/expired',
                'code'  =>101
            );
            $this->set(array(
                "error" => $error,
                "_serialize" => array("error")
            ));
        }
    }
    private function check_access_token($token) {
        if(!$token){
            return false;
        }
        $api = $this->Api->find('first',array('conditions'=>array('access_token'=>$token)));
        if(!empty($api) && time()<$api['Api']['expired']){
            return true;
        }
        return false;
    }
    private function get_info($token){
        $api = $this->Api->find('first',array('conditions'=>array('access_token'=>$token)));
        return $api;
    }
    public function customer_info(){
        $token=isset($_REQUEST['access_token'])?$_REQUEST['access_token']:"";
        $valid = $this->check_access_token($token);
        if($valid !== false){
            $check = array('card_number');
            $is_validate=true;
            $field_missing=array();
            foreach ($check as $value) {
                if(isset($_REQUEST[$value])){
                    if(!$_REQUEST[$value]){
                        $is_validate=false;
                        $field_missing[]=$value;
                    }
                }else{
                    $is_validate=false;
                    $field_missing[]=$value;
                }
            }
            if($is_validate !== true){
                $error = array(
                    'message'=>'Missing fields :'.  implode(",", $field_missing),
                    'code'  =>102
                );
                $this->set(array(
                    "error" => $error,
                    "_serialize" => array("error")
                ));
            }else{
                $this->loadModel('Customer');
                $customer = $this->Customer->findByCardNumber($_REQUEST['card_number']);
                $return = array();
                if(!empty($customer)){
                    $return=array(
                        'balance'=>$customer['Customer']['balance'],
                        'point'=>$customer['Customer']['point'],
                        'name' =>$customer['Customer']['f_name']." ".$customer['Customer']['l_name']
                    );
                }
                if(!empty($return)){
                    $this->set(array(
                        "success" => $return,
                        "_serialize" => array("success")
                    ));
                }else{
                    $error = array(
                        'message'=>'This customer is not found',
                        'code'  =>101
                    );
                    $this->set(array(
                        "error" => $error,
                        "_serialize" => array("error")
                    ));
                }
            }
            
        }else{
            $error = array(
                'message'=>'Access token invalid/expired',
                'code'  =>101
            );
            $this->set(array(
                "error" => $error,
                "_serialize" => array("error")
            ));
        }
    }
}